package com.xzzz.irda.tracker.core.adapter.elasticsearch;

import com.xzzz.common.base.util.AspectUtil;
import com.xzzz.irda.tracker.core.SpanContext;
import com.xzzz.irda.tracker.core.Tracker;
import com.xzzz.irda.tracker.core.common.TrackerConstants;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * 拦截所有方法 ES 模块的方法来实现Tracker 增强
 */
@Slf4j
@Aspect
public class TrackerElasticSearchAspect {

    @Pointcut(value = "execution(* com.xzzz.expand.es.core.EsCurdManager.*(..))")
    public void curd() {
    }

    @Pointcut(value = "execution(* com.xzzz.expand.es.core.EsIndicesManager.*(..))")
    public void indices() {
    }

    @Pointcut(value = "execution(* com.xzzz.expand.es.core.EsSearchManager.*(..))")
    public void search() {
    }

    @Around("curd() || indices() || search()")
    public Object getDoAround(ProceedingJoinPoint point) throws Throwable {
        SpanContext spanContext = null;
        try {
            String spanName = String.format("%s.%s()", AspectUtil.getClassName(point), AspectUtil.getMethodName(point));
            spanContext = Tracker.start(spanName, TrackerConstants.SPAN_TYPE_ELASTICSEARCH);

            Object index = AspectUtil.getParam(point, "index").get("index");
            if (index != null) {
                Tracker.record("index", index.toString());
            }

            Object obj;
            obj = point.proceed();
            return obj;
        } finally {
            if (spanContext != null) {
                Tracker.end();
            }
        }
    }
}
